package com.fgi.springframework.beans.factory.support;

import com.fgi.springframework.beans.BeansException;
import com.fgi.springframework.beans.factory.BeanFactory;
import com.fgi.springframework.beans.factory.config.BeanDefinition;

/**
 * @author HanXu
 * @date 2022/11/18
 * BeanDefinition注册表接口
 **/
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {


    /**
     * 通过名称获取实例(无参)
     *
     * @param name 实例名称
     * @return 实例
     * @throws BeansException bean创建异常
     */
    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    /**
     * 通过名称获取实例(有参)
     *
     * @param name 实例名称
     * @param args 构造参数
     * @return 实例
     * @throws BeansException bean创建异常
     */
    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    /**
     * 公共的获取bean方法
     *
     * @param name 实例名称
     * @param args 构造函数参数
     * @param <T> 实例类型
     * @return 实例
     */
    protected <T> T doGetBean(final String name, final Object[] args) {
        Object bean = getSingleton(name);
        if (bean != null) {
            return (T) bean;
        }

        BeanDefinition beanDefinition = getBeanDefinition(name);
        return (T) createBean(name, beanDefinition, args);
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;
}
